<!--
 * @Author: wuheng wuheng@szhbzc.com
 * @Date: 2025-02-14 10:37:48
 * @LastEditors: wuheng wuheng@szhbzc.com
 * @LastEditTime: 2025-02-25 16:58:28
 * @FilePath: \web-appc:\Users\wuheng\Desktop\WugangNew\src\centerViews\purchasing\productsummary\index.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div class="productsummary">
    <searchCard @onSearch="searchFn" @onReset="resetFn">
      <el-form :model="productsummaryFrom" label-width="auto" inline @keyup.enter="searchFn">
        <el-form-item label="到货日期：">
          <el-date-picker v-model="value1" type="daterange" range-separator="-" start-placeholder="开始时间"
            end-placeholder="结束时间" @change="timeChangeFn" />
        </el-form-item>
        <el-form-item label="SKU名称">
          <pb-input v-model="productsummaryFrom.skuName" placeholder="请输入SKU名称" />
        </el-form-item>
      </el-form>
    </searchCard>
    <div class="flex-1">
      <pb-card padding="0" height="100%">
        <ContentOperation>
          <pb-button v-hasPerm="'center:productsummary:export'" size="small" plain class="mr-6" @click="Exportexcelfn">
            导出
          </pb-button>
        </ContentOperation>
        <div class="content-box">
          <div class="table-box flex">
            <div class="left-tree-box">
              <pb-tree :style="{ maxHeight: treeH }" @nodeClick="nodeClick" class="custom-tree " :treeData="skuTreeData"
                :defaultProps="treeProps"></pb-tree>
            </div>
            <div class="table-right ">
              <pb-table :column="productsummaryColumn" :tableData="productsummaryTableData"
                :bottomElement="['pb-page']">
              </pb-table>
              <pb-pagination v-model:currentPage="pages.currentPage" v-model:pageSize="pages.pageSize"
                @onChange="onPagesChange" :total="pages.total"></pb-pagination>
            </div>
          </div>
        </div>
      </pb-card>
    </div>

  </div>
</template>
<script setup lang="ts">
import { formattedDate } from '@/utils/moment'
import { getSkuClassList } from "@/api/Sku"
import { GetSkuSummaryListApi, ExportSkuSummaryBlodApi } from '@/api/Purchasing'
const productsummaryFrom = reactive({
  deliveryStartDate: '',
  deliveryStopDate: '',
  skuName: ''
})
let NewDate = new Date() as any
const value1 = ref([formattedDate(NewDate - 7 * 24 * 60 * 60 * 1000, 'YYYY-MM-DD'), formattedDate(NewDate, 'YYYY-MM-DD')] as any)
productsummaryFrom.deliveryStartDate = value1.value[0]
productsummaryFrom.deliveryStopDate = value1.value[1]
const Exportexcelfn = () => {
  let Dates = new Date() as any
  // console.log('22', formattedDate(Dates - 7 * 24 * 60 * 60 * 1000, 'YYYY-MM-DD'))
  ExportSkuSummaryBlodApi({
    deliveryStartDate: productsummaryFrom.deliveryStartDate ? productsummaryFrom.deliveryStartDate : formattedDate(Dates - 7 * 24 * 60 * 60 * 1000, 'YYYY-MM-DD'),
    deliveryStopDate: productsummaryFrom.deliveryStopDate ? productsummaryFrom.deliveryStopDate : formattedDate(Dates, 'YYYY-MM-DD'),
    skuName: productsummaryFrom.skuName,
    skuClassCode: nodeCode.value
  }).then((response: any) => {
    const disposition = response.headers['content-disposition'];
    // const filenameMatch = disposition.match(/filename*=utf-8''\s*([^;]+)/); 没用的东西
    const parts = disposition.split("filename*=utf-8''"); // 注意这里的分割字符串，它包含了一个空的单引号来匹配格式
    const encodedFilenamePart = parts[1] ? parts[1].split(';')[0] : null; // 分割出可能包含文件名的部分，并截取到下一个分号之前
    let decodedFilename = ''
    if (encodedFilenamePart) {
      // 解码文件名
      decodedFilename = decodeURIComponent(encodedFilenamePart);
      decodedFilename = decodedFilename.replace(/\(.*?\)/, '');
      // 输出解码后的文件名
      // console.log("Decoded filename:", decodedFilename);
    }
    // else {
    //   decodedFilename = "采购汇总" + new Date().getTime() + '.xlsx'
    //   // 如果没有找到包含文件名的部分，输出警告信息
    //   // console.warn("No filename part found in the Content-Disposition header using the simplified method.");
    // }
    let blob = new Blob([response.data]);
    let downloadElement = document.createElement("a");
    let href = window.URL.createObjectURL(blob); //创建下载的链接
    // console.log(href, '22href')
    downloadElement.href = href;
    downloadElement.download = decodedFilename; //下载后文件名
    document.body.appendChild(downloadElement);
    downloadElement.click(); //点击下载
    document.body.removeChild(downloadElement); //下载完成移除元素
    window.URL.revokeObjectURL(href); //释放掉blob对象
  })
}
const pageInit = () => ({
  total: 0,
  currentPage: 1,
  pageSize: 10,
});
const pages = ref(pageInit());
const onPagesChange = () => {
  GetSummaryListFn()
}
const productsummaryTableData = ref([] as any)
const productsummaryColumn = [
  {
    key: "deliveryDate",
    name: "到货日期",
    align: "right",
  },
  {
    key: "skuName",
    name: "SKU名称",
  },
  {
    key: "skuCode",
    name: "SKU编码",
    align: "right",
  },

  {
    key: "skuClassName",
    name: "SKU类别",
  },
  {
    key: "accountingUnitName",
    name: "计量单位",
  },
  {
    key: "specifications",
    name: "规格",
  },
  {
    key: 'unitWeight',
    name: '单位重量(kg)',
    align: "right",
  },
  {
    key: 'purchaseQuantity',
    name: '采购量',
    align: "right",
  }
]
const timeChangeFn = (time: any) => {
  productsummaryFrom.deliveryStartDate = formattedDate(time[0], 'YYYY-MM-DD')
  productsummaryFrom.deliveryStopDate = formattedDate(time[1], 'YYYY-MM-DD')
}
const searchFn = () => {
  GetSummaryListFn();
}
const resetFn = () => {
  productsummaryFrom.skuName = ''
  value1.value = [formattedDate(NewDate - 7 * 24 * 60 * 60 * 1000, 'YYYY-MM-DD'), formattedDate(NewDate, 'YYYY-MM-DD')]
  productsummaryFrom.deliveryStartDate = value1.value[0]
  productsummaryFrom.deliveryStopDate = value1.value[1]
  GetSummaryListFn();
}
const nodeCode = ref("");
const nodeClick = (data) => {
  nodeCode.value = data.curNode.skuClassCode;
  GetSummaryListFn();
};
const GetSummaryListFn = () => {
  GetSkuSummaryListApi({
    "currentPage": pages.value.currentPage,
    "pageSize": pages.value.pageSize,
    ...productsummaryFrom,
    skuClassCode: nodeCode.value
  }).then(res => {
    if (res.code == 2000) {
      productsummaryTableData.value = res.data.records
      pages.value.total = res.data.total
    }
  })
}
let skuTreeData = ref([] as any);
const treeProps = { children: "children", label: "skuClassName" };

const treeH = ref(null as any);
onMounted(() => {
  getSkuClassList({
    "currentPage": 1,
    "pageSize": -1,
    "sortingFields": [
      {
        "field": "",
        "order": ""
      }
    ],
    "parentClassCode": ""
  }).then((res) => {
    skuTreeData.value = [
      {
        skuClassName: '全部',
        children: res.data.records
      }
    ];
    GetSummaryListFn()
    var height = document.getElementsByClassName("pb-table");
    treeH.value = height[0].offsetHeight + "px";

    window.addEventListener("resize", () => {
      height = document.getElementsByClassName("pb-table");
      treeH.value = height[0].offsetHeight + "px";
    });
  });
});
</script>
<style lang="scss" scoped>
.productsummary {
  .popContent {
    width: 100%;
    overflow: hidden;
  }

  .content-box {
    height: 100%;
    display: flex;
    flex-direction: column;
  }

  .table-box {
    flex: 1;

    .table-right {
      width: 84%;
      padding: 16px;
      box-sizing: border-box;
    }
  }
}
</style>
